import login from '@/utils/login/login'
import authority from '../authority'
import doRequest from './doRequest'
import loading from './loading'
import getShopId from '../getShopId'

// 错误尝试次数
const maxCount = 2

// 最终求情封装
export default async (
  options,
  { shouldLoading = true, shouldLocation = true, needLogin = false } = {}
) => {
  if (needLogin) {
    await login()
  }
  if (shouldLocation) {
    await getShopId()
  }
  if (shouldLoading) loading.show()
  for (let i = 0; i < maxCount - 1; i++) {
    try {
      const data = await doRequest(options)
      if (shouldLoading) loading.hide()
      return data
    } catch (e) {
      // 再次尝试
      if (i < maxCount) {
        // 401重新登陆
        if (e && e.statusCode === 401) {
          authority.clear()
          loading.hide(true)
        }
        continue
      }

      // 返回最终错误
      if (shouldLoading) loading.hide()
      return Promise.reject(e)
    }
  }
}
